<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue'
import { notification } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import PurchaseSelect from '../purchase/components/purchase-select.vue'
import type { SalesDetailModel } from '@/api/sales/sales-list.ts'
import { addSalesDetail, updateSalesDetail } from '@/api/sales/sales-list.ts'
import {ref} from "vue";
import ProductForm from "@/pages/product/components/product-form.vue";

const emit = defineEmits(['cancel', 'ok'])

const isUpdate = ref(false)

const visible = ref(false)

const title = computed(() => {
  return isUpdate.value ? '编辑销售单' : '新增销售单'
})

const formRef = ref<FormInstance>()

const formData = ref<SalesDetailModel>({
  salesType: 1,
  salesTotalPrice:0,
  salesActualTotalPrice:0,
  salesStatus:2,
})

const labelCol = { style: { width: '100px' } }
const wrapperCol = { span: 24 }

function open(record?: SalesDetailModel) {
  console.log('进入销售单open方法')
  visible.value = true
  isUpdate.value = !!record?.salesId
  formData.value = cloneDeep(record) ?? {
    salesId: undefined,
    salesType: 1,
    salesTotalPrice: 0,
    salesActualTotalPrice: 0,
    salesPureProfit: 0,
    salesRemarks: "",
    salesStatus: 2,
    salesPerson: "",
    purchaseId: undefined,
  }
}

async function handleOk() {
  try {
    await formRef.value?.validate()
    // 如果是编辑，则进入编辑调用接口
    if (isUpdate.value) {
      console.log(formData.value)
      // 进入新增接口
      const res = await updateSalesDetail(formData.value)
      if (res.code === 200) {
        notification.success({
          message: '修改完成',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
      visible.value = false
    }
    else {
      console.log(formData.value)
      formData.value.salesType = 1
      // 进入新增接口
      const res = await addSalesDetail(formData.value)
      if (res.code === 200) {
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
  }
  catch (errorInfo) {
    console.log('Form Validate Failed:', errorInfo)
  }
}

function handleCancel() {
  formRef.value?.resetFields()
  emit('cancel')
}


const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes
  },
})

let index = 0
const items = ref(['鲁F99999', '鲁F11111', '鲁F22222'])
const value = ref()
const inputRef = ref()
const name = ref()

function addItem(e) {
  e.preventDefault()
  console.log('addItem')
  items.value.push(name.value || `New item ${(index += 1)}`)
  name.value = ''
  setTimeout(() => {
    inputRef.value?.focus()
  }, 0)
}
const purchaseSelect = ref<InstanceType<typeof purchaseSelect>>()
const purchaseId = ref<number>()
function purchaseSelected(id: number) {
  console.log(`当前选中的产品ID是：${id}`)
  formData.value.purchaseId = id
  purchaseId.value = id
}

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" :title="title" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item name="purchaseId" :rules="[{ required: true, message: '请选择对应采购单' }]" label="所属采购单">
        <PurchaseSelect ref="purchaseSelect" @purchaseSelected="purchaseSelected" />
      </a-form-item>
      <a-form-item name="salesPerson" label="销售人" :rules="[{ required: true, message: '请填写销售人' }]">
        <a-input v-model:value="formData.salesPerson" placeholder="请填写销售人" />
      </a-form-item>
      <a-form-item name="salesRemarks" label="销售单描述">
        <a-textarea v-model:value="formData.salesRemarks" placeholder="请填写描述信息" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
